package com.splic.product.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.splic.common.config.AliPayConfig;
import com.splic.common.exception.BusinessException;
import com.splic.common.utils.SpringBeansUtil;
import com.splic.common.utils.StringUtils;
import com.splic.product.domain.Order;
import com.splic.product.dto.PayOrderDto;
import com.splic.product.dto.PayOrderReturnDto;
import com.splic.product.service.OrderService;
import com.splic.product.service.PayService;
import com.splic.product.service.ThirdPayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import static com.alipay.api.AlipayConstants.CHARSET;
import static com.alipay.api.AlipayConstants.CHARSET_UTF8;

/**
 * ==========================
 * 开发：singe
 * 创建时间：2022-03-18 21:14
 * 版本: 1.0
 * 描述：TODO
 * ==========================
 */
@Service
@Slf4j
public class PayServiceImpl implements PayService {

    @Autowired
    private OrderService orderServiceImpl;


    @Override
    public PayOrderReturnDto createPayOrder(PayOrderDto dto) {
        Order order = orderServiceImpl.getByOrderNo(dto.getOrderNo());
        if (order == null) {
            throw new BusinessException("订单不存在");
        }

        //查询支付接口是否存在
        ThirdPayService thirdpayService = SpringBeansUtil.getBean(order.getPayType() + "PayService", ThirdPayService.class);
        PayOrderReturnDto returnDto = null;//thirdpayService.createPayOrder(order, dto);
        if (returnDto == null) {
            throw new BusinessException("创建支付订单失败");
        }
        returnDto.setOrderNo(order.getOrderNo());
        return returnDto;
    }


    @Override
    public boolean checkAliPay(Map requestParams) {
        Map<String, String> params = new HashMap<String, String>();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            if(StringUtils.equals("alipay_trade_app_pay_response",name)){
                JSONObject jsonObject = (JSONObject) requestParams.get(name);
                Map map = jsonObject.getInnerMap();
                for (Iterator iter2 = map.keySet().iterator(); iter2.hasNext(); ) {
                    String name2 = (String) iter2.next();
                    params.put(name2, (String) map.get(name2));
                }
            }else{
                params.put(name, (String) requestParams.get(name));
            }
        }
        boolean flag = false;
        try {
            flag = AlipaySignature.rsaCheckV1(params, AliPayConfig.ALIPAY_PUBLIC_KEY,CHARSET_UTF8, "RSA2");
        } catch (AlipayApiException e) {
            log.error("支付宝同步通知验签失败");
            throw new BusinessException("支付宝同步通知验签失败");
        }

        if (flag){
            Order order = orderServiceImpl.getByOrderNo(params.get("out_trade_no"));
            if(order == null){
                throw new BusinessException("订单不存在");
            }
            BigDecimal amount = new BigDecimal(params.get("total_amount"));
            if(amount.compareTo(order.getAmount()) != 0){
                throw new BusinessException("订单对应金额不匹配");
            }
            if(StringUtils.equals(params.get("seller_id"),order.getUserId().toString())){
                throw new BusinessException("订单购买人不匹配");
            }
        }

        return flag;
    }
}
